<template>
	<view>
		<cu-custom :isBack="true">
			<block slot="backText">{{keyName}}</block>
		</cu-custom>
		<view class="cu-chat">
			<view v-for="(item,index) in list" :key="index" class="cu-item " :class="{'self':item.mine}">
				<view class="main">
					<view class="content shadow">
						{{item.msg}}
					</view>
				</view>
				<view class="cu-avatar radius" :style="{'background-image':`url(${item.iconUrl})`}">
				</view>
				<view class="date">{{item.date}}</view>
			</view>
		</view>

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
				v-model="msg" />
			<button class="cu-btn bg-green shadow" @tap="insertWorkOrderChat">{{$t('send')}}</button>
		</view>
	</view>
</template>

<script>
	import myConfig from '@/myConfig.js'
	import {formatDateTime} from '@/util/formatTime.js'
	import * as authUserApi from '@/api/auth/authUserApi.js'
	import * as erpWorkOrderApi from '@/api/erp/erpWorkOrderApi.js'
	import * as erpWorkOrderChatApi from '@/api/erp/erpWorkOrderChatApi.js'
	import * as erpWorkOrderTypeApi from '@/api/erp/erpWorkOrderTypeApi.js'
	import * as erpWorkOrderTypeDescribeKeyApi from '@/api/erp/erpWorkOrderTypeDescribeKeyApi.js'
	import * as erpWorkOrderTypeUserApi from '@/api/erp/erpWorkOrderTypeUserApi.js'
	import * as storage from '@/util/storage.js'
	export default {
		data() {
			return {
				workOrder: {},
				handleUser: {},
				createdUser: {},
				workOrderId: null,
				userId: storage.getUserId(),
				list: [],
				msg: '',
				interval: null,
				keyName: null
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		onLoad(option) {
			this.workOrderId = option.workOrderId
			this.keyName = option.keyName
			this.connectSocket()
			this.getWorkOrder()
		},
		methods: {
			connectSocket() {
				const accessToken = storage.getToken()
				const language = storage.getLanguage()
				const wsUrl = storage.getWebSocketUrl()
				const socketUrl =
					`${wsUrl}?accessToken=${accessToken}&language=${language}&app=iot`
				uni.connectSocket({
					url: socketUrl
				});
				uni.onSocketOpen((res) => {
					// console.log("WebSocket连接正常打开中...！");
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					this.interval = setInterval(this.bindSocket, 1000 * 60 * 60 * 2)
					this.bindSocket()
					// 注：只有连接正常打开中 ，才能正常收到消息
					uni.onSocketMessage((res) => {
						this.handleSocketData(res.data)
					});
					uni.onSocketClose((res) => {
						// console.error("关闭回调");
					})

				})
			},
			closeSocket() {
				this.unBindSocket()
				uni.closeSocket()
				clearInterval(this.interval)
				this.interval = null
			},
			bindSocket() {
				let workOrderId = this.workOrderId
				let data = {
					cmd: 'bindRoom',
					param: 'erp:workOrder:' + workOrderId
				}
				uni.sendSocketMessage({
					data: JSON.stringify(data)
				});
			},
			unBindSocket() {
				let workOrderId = this.workOrderId
				let data = {
					cmd: 'unBindRoom',
					param: 'erp:workOrder:' + workOrderId
				}
				uni.sendSocketMessage({
					data: JSON.stringify(data)
				});
			},
			handleSocketData(e) {
				let nowData = JSON.parse(e);
				if (nowData.type === 'workOrderChatInsert') {
					const item = JSON.parse(nowData.msg)
					const user = this.getUser(item.userId)
					const a = {
						'date': this.formatDateTime(item.createdDate),
						'msg': item.msg,
						'userName': user.userName,
						'iconUrl': user.iconUrl
					}
					a.mine = this.userId === user.userId
					this.list.push(a)
				}
			},
			insertWorkOrderChat() {
				erpWorkOrderChatApi.insertWorkOrderChat({
					workOrderId: this.workOrderId,
					msg: this.msg
				})
			},
			listWorkOrderChat() {
				erpWorkOrderChatApi.listWorkOrderChat({
					workOrderId: this.workOrderId,
				}).then(res => {
					const {
						data
					} = res
					const list = []
					if (data) {
						for (const item of data) {
							const user = this.getUser(item.userId)
							const a = {
								'date': this.formatDateTime(item.createdDate),
								'msg': item.msg,
								'userName': user.userName,
								'iconUrl': user.iconUrl
							}
							a.mine = this.userId === user.userId
							list.unshift(a)
						}
					}
					this.list = list
				})
			},
			getUser(userId) {
				if (userId === this.handleUser.userId) {
					return this.handleUser
				} else
				if (userId === this.createdUser.userId) {
					return this.createdUser
				} else {
					return {}
				}
			},
			formatDateTime(timestamp) {
				return formatDateTime(timestamp, this.$t('unKnow'))
			},
			getWorkOrder() {
				erpWorkOrderApi.getWorkOrder({
					workOrderId: this.workOrderId
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						this.workOrder = data
						this.getCreatedUserInfo()
					}
				})
			},
			getHandleUserInfo() {
				authUserApi.getUserWithoutToken({
					userId: this.workOrder.handleUserId
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						this.handleUser = data
						this.listWorkOrderChat()
					}

				})
			},
			getCreatedUserInfo() {
				authUserApi.getUserWithoutToken({
					userId: this.workOrder.createdUserId
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						this.createdUser = data
						this.getHandleUserInfo()
					}
				})
			},
		}
	}
</script>

<style>

</style>
